<template>
  <div class="carousel-page">
    <div class="page-header">
      <h4>宣教信息 - 轮播图</h4>
      <button class="add-btn" @click="handleAdd">增加</button>
    </div>

    <!-- 表格样式对齐药品页面，优化行高和单元格样式 -->
    <table class="data-table">
      <thead>
      <tr>
        <th>序号</th>
        <th>图片</th>
        <th>管理</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, index) in filteredList" :key="item.id">
        <td>{{ index + 1 }}</td>
        <td><img :src="item.picture" class="carousel-img" alt="轮播图"></td>
        <!-- 按钮布局参照药品页面，减少冗余容器样式 -->
        <td class="action-cell">
          <button
              :class="['status-btn', item.isused === '启用' ? 'success' : 'danger']"
              size="small"
              @click="handleStatusChange(item)"
          >
            {{ item.isused }}
          </button>
          <button
              class="edit-btn primary"
              size="small"
              @click="handleEdit(item)"
          >
            修改
          </button>
        </td>
      </tr>
      <tr v-if="filteredList.length === 0">
        <td colspan="3" class="empty-tip">暂无数据</td>
      </tr>
      </tbody>
    </table>

    <!-- 增加/编辑对话框 -->
    <div class="dialog-mask" v-if="showDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h5>{{ isEdit ? '修改轮播图' : '增加轮播图' }}</h5>
          <button class="close-btn" @click="showDialog = false">×</button>
        </div>
        <div class="dialog-content">
          <div class="image-upload-area">
            <div class="image-preview" v-if="imageUrl">
              <img :src="imageUrl" class="preview-img" alt="预览图">
            </div>
            <div class="image-placeholder" v-else>
              图片预览区域
            </div>
            <button class="upload-btn" @click="triggerFileSelect">点击上传图片</button>
            <input
                type="file"
                ref="fileInput"
                accept="image/*"
                @change="handleFileChange"
                style="display: none;"
            >
          </div>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="showDialog = false">取消</button>
          <button class="submit-btn" @click="handleSubmit">提交</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { apiClient } from '@/api/apiClient'

export default {
  name: 'XuanjiaoCarousel',
  data() {
    return {
      carouselList: [],
      filteredList: [],
      showDialog: false,
      isEdit: false,
      currentItem: null,
      imageUrl: '',
      tempImageFile: null, // 存储临时的图片文件对象
      MAX_IMAGE_SIZE: 20 * 1024 * 1024 // 20MB
    }
  },
  created() {
    this.fetchCarouselData()
  },
  methods: {
    // 获取轮播图数据
    async fetchCarouselData() {
      try {
        const res = await apiClient.get('/patient/getAllCarousel')

        if (res.data.code === 1) {
          this.carouselList = res.data.data || []
          this.filterDataByAuthority()
        } else {
          this.showToast('获取轮播图数据失败', 'error')
        }
      } catch (error) {
        console.error('获取轮播图数据出错:', error)
        this.showToast('获取数据失败，请重试', 'error')
      }
    },

    // 根据权限过滤数据
    filterDataByAuthority() {
      const userAuthority = localStorage.getItem('authority') || ''
      this.filteredList = this.carouselList.filter(
          item => item.authority === userAuthority
      )
    },

    // 计算启用的数量
    getEnabledCount() {
      return this.filteredList.filter(item => item.isused === '启用').length
    },

    // 处理增加按钮点击
    handleAdd() {
      if (this.getEnabledCount() >= 6) {
        this.showToast('启用数量太多请进行筛选', 'warning')
        return
      }

      this.isEdit = false
      this.currentItem = null
      this.imageUrl = ''
      this.tempImageFile = null
      this.showDialog = true
    },

    // 处理编辑按钮点击
    handleEdit(item) {
      this.isEdit = true
      this.currentItem = { ...item }
      this.imageUrl = item.picture
      this.tempImageFile = null
      this.showDialog = true
    },

    // 处理状态切换
    async handleStatusChange(item) {
      const newStatus = item.isused === '启用' ? '禁用' : '启用'

      // 如果是从禁用变为启用，检查数量是否超过6
      if (newStatus === '启用' && this.getEnabledCount() >= 6) {
        this.showToast('启用数量太多请进行筛选', 'warning')
        return
      }

      try {
        const res = await apiClient.post(
            '/patient/changeCarouselIsused',
            {
              id: item.id,
              isused: newStatus
            }
        )

        if (res.data.code === 1) {
          this.showToast(`已${newStatus}`, 'success')
          this.fetchCarouselData()
        } else {
          this.showToast(`操作失败: ${res.data.msg || ''}`, 'error')
        }
      } catch (error) {
        console.error('修改状态出错:', error)
        this.showToast('操作失败，请重试', 'error')
      }
    },

    // 触发文件选择
    triggerFileSelect() {
      this.$refs.fileInput.click()
    },

    // 处理文件选择
    handleFileChange(e) {
      const file = e.target.files[0]
      if (!file) return

      // 验证文件大小
      if (file.size > this.MAX_IMAGE_SIZE) {
        this.showToast('图片大小不能超过20MB', 'error')
        this.clearFileInput()
        return
      }

      // 显示预览
      this.tempImageFile = file
      const reader = new FileReader()
      reader.onload = (event) => {
        this.imageUrl = event.target.result
      }
      reader.readAsDataURL(file)

      // 清空input值，以便可以重复选择同一文件
      this.clearFileInput()
    },

    // 清空文件输入框
    clearFileInput() {
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = ''
      }
    },

    // 上传图片
    async uploadImage() {
      if (!this.tempImageFile) return null

      const formData = new FormData()
      formData.append('file', this.tempImageFile)

      try {
        const res = await apiClient.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        if (res.data.code === 1) {
          return res.data.data // 返回图片URL
        } else {
          throw new Error(res.data.msg || '上传失败')
        }
      } catch (error) {
        console.error('上传图片错误:', error)
        this.showToast(error.message || '上传失败，请重试', 'error')
        return null
      }
    },

    // 处理提交
    async handleSubmit() {
      if (!this.imageUrl) {
        this.showToast('请上传图片', 'warning')
        return
      }

      try {
        // 如果有新选择的图片，先上传
        let imageUrl = this.imageUrl
        if (this.tempImageFile) {
          const uploadedUrl = await this.uploadImage()
          if (!uploadedUrl) return // 上传失败则终止
          imageUrl = uploadedUrl
        }

        let res;
        if (this.isEdit) {
          // 修改操作
          res = await apiClient.post(
              '/patient/changeCarousel',
              {
                id: this.currentItem.id,
                picture: imageUrl
              }
          );
        } else {
          // 新增操作
          res = await apiClient.post(
              '/patient/addCarousel',
              {
                url: imageUrl,
                authority: localStorage.getItem('authority') || '',
                isused: '启用'
              }
          );
        }

        if (res.data.code === 1) {
          this.showToast(this.isEdit ? '修改成功' : '添加成功', 'success')
          this.showDialog = false
          this.fetchCarouselData()
        } else {
          this.showToast(`${this.isEdit ? '修改' : '添加'}失败: ${res.data.msg || ''}`, 'error')
        }
      } catch (error) {
        console.error('提交数据出错:', error)
        this.showToast('操作失败，请重试', 'error')
      }
    },

    // 显示提示信息（模拟Element UI的message样式）
    showToast(message, type = 'info') {
      // 实际项目中建议替换为Element UI的this.$message
      alert(`${type}: ${message}`)
    }
  }
}
</script>

<style scoped>
.carousel-page {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.add-btn {
  padding: 6px 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e0e0e0;
}

/* 参照药品页面表格样式，统一行高和垂直对齐 */
.data-table th,
.data-table td {
  padding: 8px 15px; /* 减少内边距，匹配small按钮尺寸 */
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
  vertical-align: middle; /* 关键：垂直居中对齐 */
}

/* 固定行高，确保按钮与内容对齐 */
.data-table tr {
  height: 80px;
}

.data-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  font-size: 14px;
}

/* 序号列样式 */
.data-table td:first-child {
  width: 60px;
  font-size: 14px;
}

/* 图片样式 - 控制高度与行高匹配 */
.carousel-img {
  width: 100px;
  height: 70px; /* 图片高度从40px增加到60px，匹配行高 */
  object-fit: contain; /* 改为contain，确保图片完整显示（不裁剪） */
  /* object-fit: cover; 原样式可能裁剪图片，改为contain更适合完整显示需求 */
}

/* 管理列样式 - 简化容器，减少层级 */
.action-cell {
  padding: 5px 15px;
}

/* 按钮样式完全参照Element UI的small按钮 */
.status-btn, .edit-btn {
  padding: 5px 12px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 12px; /* small按钮字体大小 */
  line-height: 1;
  margin-right: 5px; /* 按钮间距，替代gap */
}

/* 状态按钮颜色与药品页面保持一致 */
.status-btn.success {
  background-color: #52c41a; /* Element success色 */
  color: white;
}

.status-btn.danger {
  background-color: #ff4d4f; /* Element danger色 */
  color: white;
}

.edit-btn.primary {
  background-color: #1890ff; /* Element primary色 */
  color: white;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px;
}

/* 对话框增加取消按钮，与药品页面保持一致 */
.dialog-footer {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 10px; /* 按钮间距 */
}

.cancel-btn {
  padding: 8px 16px;
  background-color: #fff;
  color: #333;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 16px;
  background-color: #1890ff; /* 与药品页面提交按钮颜色一致 */
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 其他对话框样式保持不变 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-container {
  width: 90%;
  max-width: 500px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.dialog-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.dialog-content {
  padding: 20px;
}

.image-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-preview, .image-placeholder {
  width: 200px;
  height: 200px;
  border: 1px dashed #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 16px;
}
</style>